package com.example.demo.util;


import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.CollectionType;

import java.io.IOException;
import java.util.List;
import java.util.Map;


/**
 * jackson工具类
 *
 * @author SUN
 */
public abstract class JacksonUtil {
    private static final ObjectMapper MAPPER = new ObjectMapper();

    static {
        MAPPER.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
//    	MAPPER.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
    }

    /**
     * java对象转成json
     *
     * @param o
     * @return
     */
    public static String beanToJson(Object o) {
        try {
            return MAPPER.writeValueAsString(o);
        } catch (Exception e) {
            throw new RuntimeException("转换Java Bean 为 json错误", e);
        }
    }

    /**
     * json转对象
     *
     * @param t
     * @param json
     * @return
     */
    public static <T> T jsonToBean(String json, Class<T> t) {
        try {
            T obj = MAPPER.readValue(json, t);
            return obj;
        } catch (Exception e) {
            throw new RuntimeException("转换json为Java Bean错误：" + json, e);
        }
    }


    /**
     * json转list
     *
     * @param json
     * @param type
     * @return
     */
    public static <T> List<T> jsonToList(String json, Class<T> beanType) {
        try {
            CollectionType type = MAPPER.getTypeFactory().constructCollectionType(List.class, beanType);
            return MAPPER.readValue(json, type);
        } catch (Exception e) {
            throw new RuntimeException("转换json为Java List错误：" + json, e);
        }
    }


    /**
     * 返回一个JsonNode对象
     *
     * @param json
     * @return
     */
    public static JsonNode readTree(String json) {
        try {
            return MAPPER.readTree(json);
        } catch (IOException e) {
            throw new RuntimeException("转换json为JsonNode错误：" + json, e);
        }
    }


    /**
     * bean转map
     *
     * @param bean
     * @return
     */
    @SuppressWarnings("unchecked")
    public static Map<String, Object> beanToMap(Object bean) {
        return MAPPER.convertValue(bean, Map.class);
    }

    public static void main(String[] args) throws IOException {
//        String json = "{\"code\": 1,\"message\":\"成功\",\"data\":{\"id\":\"1\",\"name\":\"test\"}}";
//        JsonNode node = MAPPER.readTree(json);
//        System.out.println(node.get("code").asInt());
//        LoginUser u = jsonToBean(node.findValue("data").toString(), LoginUser.class);
//        System.out.println(u);
    }
}
